package org.goodev.arch;

import android.arch.lifecycle.LiveData;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class LocationLiveData extends LiveData<Location> {
    private static final String TAG = "LiveData";
    private LocationManager locationManager;
    private static LocationLiveData sIns;

    public static LocationLiveData getsIns(Context context) {
        if (sIns == null) {
            sIns = new LocationLiveData(context.getApplicationContext());
        }
        return sIns;
    }

    private LocationListener listener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG, "onLocationChanged() called with: location = [" + location + "]");
            setValue(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

    private LocationLiveData(Context context) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    protected void onActive() {
        Log.d(TAG, "onActive() called");
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, listener);
    }

    @Override
    protected void onInactive() {
        Log.d(TAG, "onInactive() called");
        locationManager.removeUpdates(listener);
    }
}
